﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using InfoSoftGlobal;
using System.Web.Security;
using System.Configuration;

namespace websitev2.Controllers
{
    public class StatsController : Controller
    {
        //
        // GET: /Stats/

        public Models.StartStopEntities db = new Models.StartStopEntities();

        public ActionResult Index()
        {
            return View();
        }


        /// <summary>
        /// User stats
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        new public ActionResult User(string ID)
        {
            if (ID == null)
            {
                return RedirectToAction("index", "home");
            }

            // Load the user. 
            var user = db.ssUsers.FirstOrDefault(u => u.UserName == ID);

            if (user == null)
            {
                // Really we should send this to a user not found page. 
                return RedirectToAction("index", "home");
            }

            try
            {
                // Load the general information 
                Models.UserGeneralInformationModel oUserGen = new Models.UserGeneralInformationModel();

                oUserGen = websitev2.Core.UserCore.LoadUserGen(user.UserGUID.GetValueOrDefault());
                ViewBag.UserGen = oUserGen;
                ViewBag.MediumAvatar = Core.UserCore.ReturnAvatarURL(user.UserGUID.GetValueOrDefault(), 1);

                // Load the top ten apps by time 
                ViewBag.TopTen = websitev2.Core.UserCore.ReturnAppUsage(user.UserID, 7, 6);
                ViewBag.UserTrophies = websitev2.Core.UserCore.ReturnUserTrophy(user.UserID, 3, true);
                ViewBag.UserTrophiesProgress = websitev2.Core.UserCore.ReturnUserTrophy(user.UserID, 10, false);

                #region Graphs

                ViewBag.UGraphHTML = FusionCharts.RenderChartHTML("/content/fusioncharts/StackedArea2D.swf", "", Core.ChartBuilder.GenerateXMLforUsageArea(30, user.UserID), "usage", "920", "250", false);
                ViewBag.uTodayPie = FusionCharts.RenderChartHTML("/content/fusioncharts/Doughnut2d.swf", "", Core.ChartBuilder.GenerateXMLforUsagePie(Convert.ToInt32(oUserGen.TimeSpentWorking.TotalMinutes), Convert.ToInt32(oUserGen.TimeSpentPlaying.TotalMinutes), Convert.ToInt32(oUserGen.TimeSpentBrowsing.TotalMinutes)), "usagepie", "250", "250", false);

                #endregion

                #region SEO
                // SEO Studd
                ViewBag.Title = user.UserName + "s profile, trophies, stats and award progress | Startstop.me, all your stats in one place";
                #endregion

                // Only populate the objects IF the session is authenticated! 
                // This is so that displayed information can be changed for a logged on user.
                if (Request.IsAuthenticated)
                {

                    // We need to run some checks to make sure the session object is populates
                    Guid UserGUID = Guid.Parse(Membership.GetUser().ProviderUserKey.ToString());

                    // next we load the loggedinuser information into the session as we'll be needing it
                    Models.User.LoggedIn oLogged = Core.UserCore.LoadLoggedInUserDetails(UserGUID);
                    // Populate the user session.
                    Session["oLogged"] = oLogged;
                    Session["oUsername"] = oLogged.UserName;

                }


                // Load the generic stats panel for the curent user
                List<StartStop.ServiceResources.StatOverView> oList = StartStop.Helpers.UserStatLog.ReturnActiveStats(user.UserID);
                ViewBag.GenericStatsList = oList;

                // Load the stats which the user doesn't currently have so they can add them to their account
                List<StartStop.ServiceResources.StatOverView> oList2 = StartStop.Helpers.DetailedStatOverview.ReturnListOfOverviewStatsUserHasNoRecordsFor(user.UserID);
                ViewBag.GenericStatsListToAdd = oList2;

                ViewBag.StartStopDownloadLink = ConfigurationManager.AppSettings["Downloads.StartStop"].ToString();

            }
            catch (Exception ex)
            {
                StartStop.ServiceResources.ErrorEvent oErrorEvent = new StartStop.ServiceResources.ErrorEvent();

                oErrorEvent.ErrorDetail = ex.Message.ToString();
                oErrorEvent.ErrorFrom = StartStop.ServiceResources.ErrorEvent.ErrorOriginatedFrom.UserSite;
                oErrorEvent.ErrorLevel = StartStop.ServiceResources.ErrorEvent.ErrorLevelType.Critical;
                oErrorEvent.ErrorMessage = "User page died";
                oErrorEvent.Method = "new public ActionResult User(string ID)";
                StartStop.Helpers.EventLog.LogError(oErrorEvent);
                return RedirectToAction("apperror", "errors");
            }


            return View(user);
        }


        /// <summary>
        /// Return App Details
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public ActionResult App(string ID)
        {
            if (ID == null)
            {
                return RedirectToAction("index", "home");
            }


            var app = db.WindowAppLists.FirstOrDefault(a => a.Description == ID.Replace("-", " "));

            #region Find The application
            // Check to make sure it's not null
            if (app == null)
            {
                // there must be a better way of detecting if something is a certain type or can be parsed.
                try
                {
                    Int64 _trytolocatethroughID = Int64.Parse(ID);
                    // Could be an ID
                    app = db.WindowAppLists.FirstOrDefault(a => a.AppID == _trytolocatethroughID);
                }
                catch
                {
                    // probably not an ID! 
                }
            }

            // just in case
            if (app == null)
            {
                // maybe we should send them to some kind of search pagehere... 
                return RedirectToAction("index", "home");
            }
            #endregion


            #region populate scalar items

            ViewBag.AppUsers = websitev2.Core.SqlAccessCore.ExecuteScalar(@"SELECT  COUNT(DIStinct [UserID] )  FROM UsersAppLog where AppID = " + app.AppID);
            ViewBag.TrophyCount = websitev2.Core.SqlAccessCore.ExecuteScalar(@"select count (*) from [WindowAppTrophyLink] where AppID=" + app.AppID);

            #endregion


            ViewBag.AppTrophies = websitev2.Core.UserCore.ReturnAppTrophy(app.AppID);

            ViewBag.Comments = db.WindowAppComments
                .Where(a => a.AppID == app.AppID);

            // Graphs
            ViewBag.AppUsageGraph = FusionCharts.RenderChartHTML("/content/fusioncharts/Column3d.swf", "", Core.ChartBuilder.GenerateXMLforAppUsage(app.AppID, 30, false, 0), "usage", "920", "250", false);

            // Populate Complex Models.
            ViewBag.AppInfo = Core.App.GetAppDetails(app.AppID);


            #region page SEO
            ViewBag.Title = app.Signature + ".exe - " + app.Description + " stats, description, trophies, questions, answers and rating  | Startstop.me, all your stats in one place";
            if (app.LongDescription != null)
            {
                ViewBag.Description = app.LongDescription;
            }
            else
            {
                ViewBag.Description = ViewBag.Title;
            }
            ViewBag.Keywords = "stats,statistics," + app.Signature + ".exe," + app.Signature + ", information,users,trophies,acheivements";
            #endregion

            // We store this for when we need to upload an image... This should be changed to we use some kind of routing variables but at the moment, I'm not sure how to do it. 
            Session["AppID"] = app.AppID;

            #region Appcomment info
            List<SelectListItem> CommentType = new List<SelectListItem>();
            CommentType.Add(new SelectListItem
            {
                Text = "Comment",
                Value = "1"
            });
            CommentType.Add(new SelectListItem { Text = "Question", Value = "2" });

            ViewBag.CommentType = CommentType;
            #endregion

            return View(ViewBag.AppInfo);
        }

        public ActionResult PS3(string ID)
        {
            // We should make this generic, so it works for all the different kinds of stats
            ViewBag.TrophyCount = 0;
            ViewBag.AppUsers = 0;

            
            StartStop.ServiceResources.MessageResponse oFind = StartStop.Helpers.DetailedStatOverview.FindOverviewIDFromTitle(ID);
            
            // Cannot find it from the title.
            if (!oFind.Success)
            {
                // try to see if an INT has been passed.
                try
                {
                    oFind.ReturnID = int.Parse(ID);
                    oFind.Success = true;
                }
                catch
                { }
            }


            if (oFind.Success)
            {
                var info = StartStop.Helpers.DetailedStatOverview.LoadOverview(oFind.ReturnID);
                
                // Names the same as the win app one. This will make it easier to update the gfx if necessary
                ViewBag.AppTrophies = StartStop.Helpers.Trophy.SpecificListOfTrophies((int)oFind.ReturnID, 2);
                // Returns the count of items for that thing. 
                ViewBag.TrophyCount = ViewBag.AppTrophies.Count; 

                return View(info); 
            }
            else
            {
                // Really we should shoot them off to a list of detail stats but we're still writing that innit. 
                Response.Redirect("/"); 
            }
            return View();
        }

        public ActionResult Trophies(string ID, string ID2)
        {
            return View(); 
        }

        #region To Do
        [HttpPost]
        // TO DO! 
        public ActionResult App(Models.Stats.AppComments oComment)
        {



            return View();
        }
        #endregion
    }
}
